/*
 * @Author: zhi1hw hanwei@zhi1tech.com
 * @Date: 2024-06-18 10:32:15
 * @LastEditors: zhi1hw hanwei@zhi1tech.com
 * @LastEditTime: 2024-08-05 14:26:20
 * @FilePath: \code\src\utils\common.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
export interface IUtils {
  setCheckDomColor: (dom: string, attrName: string, attrColor: string) => void;
  getUrlParam: () => void;
  phoneReg: (inputString: string, requestId?:string) => string;
  extractUrls: (inputString: string) => void;
  getFileSize: (url:string) => Promise<string>
}
export const utils: IUtils = {
  /**
   * 修改指定dom属性
   */
  setCheckDomColor(dom: string, attrName: string, attrColor: string) {
    if (document.querySelector(dom)) {
      (document.querySelector(dom) as HTMLElement).style.setProperty(attrName, attrColor);
    }
  },
  /**
   * 获取路径参数
   */
  getUrlParam() {
    // 获取当前页面的完整 URL
    const currentURL = window.location.href;

    // 使用正则表达式匹配 URL 中的查询参数部分
    const parameterMatch = currentURL.match(/\?(.*)/);

    if (parameterMatch) {
      // 如果有匹配到参数部分
      const queryString = parameterMatch[1];

      // 将查询参数字符串解析为对象
      const params: Record<string, string> = {};
      queryString.split('&').forEach(pair => {
        const [key, value] = pair.split('=');
        params[key] = decodeURIComponent(value);
      });
      return params
    }
  },
  /**
   * 查找并插入a标签
   * 
   * 本函数通过正则表达式查找手机号和客服号并且添加a标签。
   * 
   * @param inputString 需要匹配电话的字符串
   * @returns 。
   */
  phoneReg(inputString: string, requestId:string = '') {
    // 
    // 正则表达式匹配以 "400" 开头的服务电话（包含后面的字符）
    // (https?:\/\/[^\s<>\[\]]+)|
    const regex400 = /1[3-9]\d{9}|((\d*){1,3}[-|\s]+){1,}\d+|<ref(.*?)>(.*?)<\/ref>*/g;
    // 匹配以 "400" 开头的服务电话（包含后面的字符）
    const customerServiceMatches = inputString.match(regex400);
    const newArr = new Set(customerServiceMatches);
    console.log(newArr)

    if (newArr) {
      // 在字符串中标记400服务电话
      newArr.forEach(match => {
        if(match.startsWith('http')) {
          inputString = inputString.replace(match, `<a href="${match}"  style="color: #5cb2ff;" target="_blank">${match}</a>`)
        } else if(match.startsWith('1') || match.startsWith('400')) {
          // Escape special characters in the match string to prevent regex injection
          const escapedMatch = match.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
          const regex = new RegExp(escapedMatch, 'g');
          inputString = inputString.replace(regex, `<a href="tel: ${match}" style="text-decoration: underline;color: #5cb2ff;display:contents">${match}</a>`);
        } else if(match.startsWith('<ref')) {
          const regex = /<ref>(.*?)<\/ref>/g;
          const refContent = regex.exec(match);
          inputString = refContent && refContent.length > 1 ?inputString.replace(match, `<ref class="doc-tips" data-position="${requestId}%${refContent[1]}" style="display: contents;color:#999999">${refContent[1]}</ref>`) : '';
        }
      });
    }
    return inputString
  },

  // 提取字符串中的网址并插入a标签
  extractUrls(inputString: string) {
    // 正则表达式匹配网址
    const regexUrl = /(https?:\/\/[^\s]+)/g;
    // 匹配网址
    const urlMatches = inputString.match(regexUrl);
    if (urlMatches) {
      // 在字符串中标记网址
      urlMatches.forEach((match: string) => {
        inputString = inputString.replace(match, `<a href="${match}" target="_blank"`)
      })
    }
  },

  getFileSize(url:string) {
    return new Promise(function (resolve, reject) {
      const xhr = new XMLHttpRequest();
      xhr.open("HEAD", url);
      xhr.onreadystatechange = function () {
        if (this.readyState === this.DONE) {
          if (this.status === 200) {
            const size = xhr.getResponseHeader("Content-Length") || '';
            resolve(size);
          } else {
            reject("Failed to get file size.");
          }
        }
      };
      xhr.send();
    });
  }
  
};
